package com.rent.house.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rent.common.entity.ResponseResult;
import com.rent.house.pojo.entity.Pic;
import com.rent.house.service.PicService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/pic")
@Api(tags = "图片管理")
@RequiredArgsConstructor
public class PicController {

    private final PicService picService;

    @ApiOperation("房源图片上传")
    @PostMapping("/upload")
    public ResponseResult<Pic> upload(
            @ApiParam("图片文件")@RequestParam MultipartFile file,
            @ApiParam("房源ID") @RequestParam Long houseId,
            @ApiParam("是否主图") @RequestParam(required = false, defaultValue = "false") Boolean isMain
    )
    {
        return ResponseResult.success(picService.uploadHousePic(file, houseId, isMain));
    }

    @GetMapping("/list")
    @ApiOperation("图片列表查询")
    public ResponseResult<Page<Pic>> listPics(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNo,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("房源ID") @RequestParam(required = false) Long houseId) {
        Page<Pic> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Pic> queryWrapper = new QueryWrapper<>();
        if (houseId != null) {
            queryWrapper.eq("house_id", houseId);
        }
        queryWrapper.orderByDesc("create_time");
        Page<Pic> result = picService.listPics(page, queryWrapper);
        return ResponseResult.success(result);
    }


    @DeleteMapping("/{id}")
    public ResponseResult<Void> delete(@PathVariable Long id) {
        picService.deletePic(id);
        return ResponseResult.success();
    }
}
